<template>
  <div class="sandbox">
    <el-row :gutter="20">
      <el-col :span="24">
        <el-card class="sandbox-card">
          <template #header>
            <div class="card-header">
              <span>代码沙盒环境</span>
              <div class="header-actions">
                <el-select v-model="selectedLanguage" placeholder="选择编程语言" style="width: 150px; margin-right: 10px;">
                  <el-option label="JavaScript" value="javascript" />
                  <el-option label="Python" value="python" />
                  <el-option label="Java" value="java" />
                  <el-option label="C++" value="cpp" />
                  <el-option label="Go" value="go" />
                </el-select>
                <el-button type="primary" @click="runCode" :loading="running">
                  运行代码
                </el-button>
                <el-button @click="clearCode">清空代码</el-button>
              </div>
            </div>
          </template>
          
          <el-row :gutter="20">
            <el-col :span="12">
              <div class="code-editor-section">
                <h3>代码编辑器</h3>
                <el-input
                  v-model="code"
                  type="textarea"
                  :rows="20"
                  placeholder="在这里输入你的代码..."
                  class="code-editor"
                  spellcheck="false"
                />
              </div>
            </el-col>
            
            <el-col :span="12">
              <div class="output-section">
                <h3>执行结果</h3>
                <div class="output-container">
                  <div v-if="output" class="output-content">
                    <pre>{{ output }}</pre>
                  </div>
                  <div v-else class="no-output">
                    <el-empty description="暂无执行结果" />
                  </div>
                </div>
                
                <div class="execution-info" v-if="executionInfo">
                  <el-divider content-position="left">执行信息</el-divider>
                  <el-descriptions :column="1" size="small" border>
                    <el-descriptions-item label="执行时间">{{ executionInfo.executionTime }}ms</el-descriptions-item>
                    <el-descriptions-item label="内存使用">{{ executionInfo.memoryUsage }}MB</el-descriptions-item>
                    <el-descriptions-item label="状态">{{ executionInfo.status }}</el-descriptions-item>
                  </el-descriptions>
                </div>
              </div>
            </el-col>
          </el-row>
        </el-card>
      </el-col>
    </el-row>

    <el-row :gutter="20" style="margin-top: 20px;">
      <el-col :span="24">
        <el-card class="examples-card">
          <template #header>
            <div class="card-header">
              <span>代码示例</span>
              <el-button @click="loadExample" type="primary" plain>加载示例</el-button>
            </div>
          </template>
          
          <el-tabs v-model="activeExampleTab" type="border-card">
            <el-tab-pane label="JavaScript" name="javascript">
              <div class="example-content">
                <h4>基础示例</h4>
                <el-button @click="loadExampleCode('javascript', 'basic')" type="text">Hello World</el-button>
                <el-button @click="loadExampleCode('javascript', 'array')" type="text">数组操作</el-button>
                <el-button @click="loadExampleCode('javascript', 'async')" type="text">异步处理</el-button>
                
                <h4>算法示例</h4>
                <el-button @click="loadExampleCode('javascript', 'sort')" type="text">排序算法</el-button>
                <el-button @click="loadExampleCode('javascript', 'search')" type="text">搜索算法</el-button>
                <el-button @click="loadExampleCode('javascript', 'recursion')" type="text">递归示例</el-button>
              </div>
            </el-tab-pane>
            
            <el-tab-pane label="Python" name="python">
              <div class="example-content">
                <h4>基础示例</h4>
                <el-button @click="loadExampleCode('python', 'basic')" type="text">Hello World</el-button>
                <el-button @click="loadExampleCode('python', 'list')" type="text">列表操作</el-button>
                <el-button @click="loadExampleCode('python', 'function')" type="text">函数定义</el-button>
                
                <h4>数据处理</h4>
                <el-button @click="loadExampleCode('python', 'file')" type="text">文件操作</el-button>
                <el-button @click="loadExampleCode('python', 'json')" type="text">JSON处理</el-button>
              </div>
            </el-tab-pane>
            
            <el-tab-pane label="Java" name="java">
              <div class="example-content">
                <h4>基础示例</h4>
                <el-button @click="loadExampleCode('java', 'basic')" type="text">Hello World</el-button>
                <el-button @click="loadExampleCode('java', 'class')" type="text">类定义</el-button>
                <el-button @click="loadExampleCode('java', 'collection')" type="text">集合操作</el-button>
              </div>
            </el-tab-pane>
          </el-tabs>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import { ref, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { executeCode } from '@/utils/sandbox'

const selectedLanguage = ref('javascript')
const code = ref('')
const output = ref('')
const running = ref(false)
const executionInfo = ref(null)
const activeExampleTab = ref('javascript')

// 代码示例
const examples = {
  javascript: {
    basic: `// Hello World 示例
console.log("Hello, World!");
console.log("欢迎使用代码沙盒!");

// 变量声明
let name = "开发者";
const greeting = \`你好, \${name}!\`;
console.log(greeting);

// 简单计算
let a = 10;
let b = 20;
console.log(\`\${a} + \${b} = \${a + b}\`);
console.log(\`\${a} * \${b} = \${a * b}\`);`,
    
    array: `// 数组操作示例
const numbers = [1, 2, 3, 4, 5];
console.log("原始数组:", numbers);

// 数组方法
const doubled = numbers.map(x => x * 2);
console.log("翻倍后:", doubled);

const evenNumbers = numbers.filter(x => x % 2 === 0);
console.log("偶数:", evenNumbers);

const sum = numbers.reduce((acc, curr) => acc + curr, 0);
console.log("总和:", sum);

// 排序
const sorted = [...numbers].sort((a, b) => b - a);
console.log("降序排列:", sorted);`,
    
    async: `// 异步处理示例
async function fetchData() {
  console.log("开始获取数据...");
  
  // 模拟异步操作
  const data = await new Promise(resolve => {
    setTimeout(() => {
      resolve({ id: 1, name: "示例数据", timestamp: Date.now() });
    }, 1000);
  });
  
  console.log("获取到的数据:", data);
  return data;
}

// 调用异步函数
fetchData().then(result => {
  console.log("异步操作完成:", result);
}).catch(error => {
  console.error("发生错误:", error);
});

console.log("异步函数调用完成");`,
    
    sort: `// 排序算法示例
function bubbleSort(arr) {
  const n = arr.length;
  let swapped;
  
  do {
    swapped = false;
    for (let i = 0; i < n - 1; i++) {
      if (arr[i] > arr[i + 1]) {
        [arr[i], arr[i + 1]] = [arr[i + 1], arr[i]];
        swapped = true;
      }
    }
  } while (swapped);
  
  return arr;
}

function quickSort(arr) {
  if (arr.length <= 1) return arr;
  
  const pivot = arr[Math.floor(arr.length / 2)];
  const left = arr.filter(x => x < pivot);
  const middle = arr.filter(x => x === pivot);
  const right = arr.filter(x => x > pivot);
  
  return [...quickSort(left), ...middle, ...quickSort(right)];
}

// 测试排序
const testArray = [64, 34, 25, 12, 22, 11, 90];
console.log("原始数组:", testArray);

const bubbleSorted = bubbleSort([...testArray]);
console.log("冒泡排序:", bubbleSorted);

const quickSorted = quickSort([...testArray]);
console.log("快速排序:", quickSorted);`,
    
    search: `// 搜索算法示例
function linearSearch(arr, target) {
  for (let i = 0; i < arr.length; i++) {
    if (arr[i] === target) {
      return i;
    }
  }
  return -1;
}

function binarySearch(arr, target) {
  let left = 0;
  let right = arr.length - 1;
  
  while (left <= right) {
    const mid = Math.floor((left + right) / 2);
    if (arr[mid] === target) {
      return mid;
    } else if (arr[mid] < target) {
      left = mid + 1;
    } else {
      right = mid - 1;
    }
  }
  return -1;
}

// 测试搜索
const sortedArray = [1, 3, 5, 7, 9, 11, 13, 15];
const target = 7;

console.log("数组:", sortedArray);
console.log("目标值:", target);

const linearResult = linearSearch(sortedArray, target);
console.log(\`线性搜索结果: 索引 \${linearResult}\`);

const binaryResult = binarySearch(sortedArray, target);
console.log(\`二分搜索结果: 索引 \${binaryResult}\`);`,
    
    recursion: `// 递归示例
function factorial(n) {
  if (n <= 1) return 1;
  return n * factorial(n - 1);
}

function fibonacci(n) {
  if (n <= 1) return n;
  return fibonacci(n - 1) + fibonacci(n - 2);
}

function gcd(a, b) {
  if (b === 0) return a;
  return gcd(b, a % b);
}

// 测试递归函数
console.log("阶乘计算:");
for (let i = 0; i <= 10; i++) {
  console.log(\`\${i}! = \${factorial(i)}\`);
}

console.log("\\n斐波那契数列:");
for (let i = 0; i <= 10; i++) {
  console.log(\`F(\${i}) = \${fibonacci(i)}\`);
}

console.log("\\n最大公约数:");
console.log(\`GCD(48, 18) = \${gcd(48, 18)}\`);
console.log(\`GCD(54, 24) = \${gcd(54, 24)}\`);`
  },
  
  python: {
    basic: `# Hello World 示例
print("Hello, World!")
print("欢迎使用Python代码沙盒!")

# 变量声明
name = "开发者"
greeting = f"你好, {name}!"
print(greeting)

# 简单计算
a = 10
b = 20
print(f"{a} + {b} = {a + b}")
print(f"{a} * {b} = {a * b}")

# 列表操作
numbers = [1, 2, 3, 4, 5]
print(f"列表: {numbers}")
print(f"列表长度: {len(numbers)}")
print(f"第一个元素: {numbers[0]}")
print(f"最后一个元素: {numbers[-1]}")`,
    
    list: `# 列表操作示例
numbers = [1, 2, 3, 4, 5]
print("原始列表:", numbers)

# 列表推导式
squares = [x**2 for x in numbers]
print("平方数:", squares)

even_numbers = [x for x in numbers if x % 2 == 0]
print("偶数:", even_numbers)

# 列表方法
numbers.append(6)
print("添加元素后:", numbers)

numbers.insert(0, 0)
print("插入元素后:", numbers)

numbers.sort(reverse=True)
print("降序排列:", numbers)

# 切片操作
print("前三个元素:", numbers[:3])
print("后三个元素:", numbers[-3:])
print("偶数索引元素:", numbers[::2])`,
    
    function: `# 函数定义示例
def greet(name, greeting="你好"):
    """问候函数"""
    return f"{greeting}, {name}!"

def calculate_area(length, width):
    """计算矩形面积"""
    area = length * width
    perimeter = 2 * (length + width)
    return area, perimeter

def fibonacci(n):
    """计算斐波那契数列"""
    if n <= 1:
        return n
    return fibonacci(n-1) + fibonacci(n-2)

# 调用函数
print(greet("世界"))
print(greet("朋友", "早上好"))

area, perimeter = calculate_area(5, 3)
print(f"矩形面积: {area}, 周长: {perimeter}")

print("斐波那契数列:")
for i in range(10):
    print(f"F({i}) = {fibonacci(i)}")`,
    
    file: `# 文件操作示例
import os

# 创建临时文件
filename = "temp_example.txt"

# 写入文件
with open(filename, 'w', encoding='utf-8') as f:
    f.write("这是第一行\\n")
    f.write("这是第二行\\n")
    f.write("这是第三行\\n")

print(f"文件 {filename} 创建成功")

# 读取文件
with open(filename, 'r', encoding='utf-8') as f:
    content = f.read()
    print("文件内容:")
    print(content)

# 按行读取
with open(filename, 'r', encoding='utf-8') as f:
    lines = f.readlines()
    print("\\n按行读取:")
    for i, line in enumerate(lines, 1):
        print(f"第{i}行: {line.strip()}")

# 删除临时文件
os.remove(filename)
print(f"\\n文件 {filename} 已删除")`,
    
    json: `# JSON处理示例
import json

# 创建数据
data = {
    "name": "张三",
    "age": 25,
    "city": "北京",
    "skills": ["Python", "JavaScript", "Vue"],
    "projects": [
        {"name": "项目A", "status": "完成"},
        {"name": "项目B", "status": "进行中"}
    ]
}

# 转换为JSON字符串
json_string = json.dumps(data, ensure_ascii=False, indent=2)
print("JSON字符串:")
print(json_string)

# 解析JSON字符串
parsed_data = json.loads(json_string)
print("\\n解析后的数据:")
print(f"姓名: {parsed_data['name']}")
print(f"年龄: {parsed_data['age']}")
print(f"技能: {', '.join(parsed_data['skills'])}")

# 更新数据
parsed_data['age'] = 26
parsed_data['skills'].append('React')

print("\\n更新后的数据:")
print(json.dumps(parsed_data, ensure_ascii=False, indent=2))`
  },
  
  java: {
    basic: `// Hello World 示例
public class HelloWorld {
    public static void main(String[] args) {
        System.out.println("Hello, World!");
        System.out.println("欢迎使用Java代码沙盒!");
        
        // 变量声明
        String name = "开发者";
        String greeting = "你好, " + name + "!";
        System.out.println(greeting);
        
        // 简单计算
        int a = 10;
        int b = 20;
        System.out.println(a + " + " + b + " = " + (a + b));
        System.out.println(a + " * " + b + " = " + (a * b));
        
        // 数组操作
        int[] numbers = {1, 2, 3, 4, 5};
        System.out.println("数组长度: " + numbers.length);
        System.out.println("第一个元素: " + numbers[0]);
        System.out.println("最后一个元素: " + numbers[numbers.length - 1]);
    }
}`,
    
    class: `// 类定义示例
public class Person {
    private String name;
    private int age;
    
    // 构造函数
    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }
    
    // Getter方法
    public String getName() {
        return name;
    }
    
    public int getAge() {
        return age;
    }
    
    // Setter方法
    public void setName(String name) {
        this.name = name;
    }
    
    public void setAge(int age) {
        this.age = age;
    }
    
    // 重写toString方法
    @Override
    public String toString() {
        return "Person{name='" + name + "', age=" + age + "}";
    }
    
    public static void main(String[] args) {
        Person person1 = new Person("张三", 25);
        Person person2 = new Person("李四", 30);
        
        System.out.println("人员信息:");
        System.out.println(person1);
        System.out.println(person2);
        
        // 修改信息
        person1.setAge(26);
        System.out.println("\\n修改后: " + person1);
    }
}`,
    
    collection: `// 集合操作示例
import java.util.*;

public class CollectionDemo {
    public static void main(String[] args) {
        // List示例
        List<String> names = new ArrayList<>();
        names.add("张三");
        names.add("李四");
        names.add("王五");
        
        System.out.println("姓名列表: " + names);
        System.out.println("列表大小: " + names.size());
        System.out.println("第一个姓名: " + names.get(0));
        
        // Set示例
        Set<Integer> numbers = new HashSet<>();
        numbers.add(1);
        numbers.add(2);
        numbers.add(3);
        numbers.add(2); // 重复元素不会被添加
        
        System.out.println("\\n数字集合: " + numbers);
        System.out.println("集合大小: " + numbers.size());
        
        // Map示例
        Map<String, Integer> scores = new HashMap<>();
        scores.put("张三", 85);
        scores.put("李四", 92);
        scores.put("王五", 78);
        
        System.out.println("\\n成绩映射:");
        for (Map.Entry<String, Integer> entry : scores.entrySet()) {
            System.out.println(entry.getKey() + ": " + entry.getValue());
        }
        
        // 排序
        List<Integer> scoreList = new ArrayList<>(scores.values());
        Collections.sort(scoreList, Collections.reverseOrder());
        System.out.println("\\n成绩排序: " + scoreList);
    }
}`
  }
}

// 监听语言变化
watch(selectedLanguage, (newLang) => {
  // 可以在这里添加语言切换的逻辑
  console.log('切换到语言:', newLang)
})

const runCode = async () => {
  if (!code.value.trim()) {
    ElMessage.warning('请输入代码')
    return
  }

  running.value = true
  output.value = ''
  executionInfo.value = null

  try {
    const result = await executeCode(code.value, selectedLanguage.value)
    output.value = result.output
    executionInfo.value = {
      executionTime: result.executionTime,
      memoryUsage: result.memoryUsage,
      status: result.status
    }
    ElMessage.success('代码执行成功')
  } catch (error) {
    output.value = `执行错误: ${error.message}`
    ElMessage.error('代码执行失败')
  } finally {
    running.value = false
  }
}

const clearCode = () => {
  code.value = ''
  output.value = ''
  executionInfo.value = null
  ElMessage.info('代码已清空')
}

const loadExample = () => {
  // 根据当前选择的语言加载示例
  const lang = selectedLanguage.value
  if (examples[lang]) {
    const firstExample = Object.keys(examples[lang])[0]
    loadExampleCode(lang, firstExample)
  }
}

const loadExampleCode = (language, exampleKey) => {
  if (examples[language] && examples[language][exampleKey]) {
    code.value = examples[language][exampleKey]
    selectedLanguage.value = language
    ElMessage.success('示例代码已加载')
  }
}
</script>

<style scoped>
.sandbox {
  max-width: 1200px;
  margin: 0 auto;
}

.sandbox-card, .examples-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-actions {
  display: flex;
  align-items: center;
}

.code-editor-section, .output-section {
  height: 100%;
}

.code-editor-section h3, .output-section h3 {
  margin-bottom: 15px;
  color: #303133;
}

.code-editor {
  font-family: 'Courier New', monospace;
  font-size: 14px;
  line-height: 1.5;
}

.output-container {
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  min-height: 300px;
  background-color: #f5f7fa;
}

.output-content {
  padding: 15px;
}

.output-content pre {
  margin: 0;
  font-family: 'Courier New', monospace;
  font-size: 14px;
  line-height: 1.5;
  white-space: pre-wrap;
  word-wrap: break-word;
}

.no-output {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 300px;
}

.execution-info {
  margin-top: 20px;
}

.example-content h4 {
  margin: 15px 0 10px 0;
  color: #606266;
}

.example-content .el-button {
  margin-right: 10px;
  margin-bottom: 5px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .card-header {
    flex-direction: column;
    gap: 10px;
    align-items: flex-start;
  }
  
  .header-actions {
    flex-wrap: wrap;
    gap: 10px;
  }
  
  .code-editor-section, .output-section {
    margin-bottom: 20px;
  }
}
</style>
